#include "FileTest.h"
#include <stdio.h>
#include <string.h>

/*
 * Created: 2/24/12; CGP
 
 a) Create a new file (opened for writing)
 b) Write 100 bytes of data into the file by writing the data as single bytes. 
    That is, you should have a loop that calls your File Write method 100 times, each time, 
    writing a single byte of data. Write at least some different bytes.
 c) Close the file
 d) Open the same file for reading
 e) Read 100 bytes of data from the file by reading the data as single bytes. 
    That is, you should have a loop that calls your File Read method 100 times, each time, 
    reading a single byte of data. Make sure that the data is the same as written.
 f) Make sure that when you read past the end of the file, you can't read more data. (i.e., 
    End of File is detected correctly).
 */

#define NUMBER_WRITES 100

int main() {
    int length;
    printf("Starting test...\n"); fflush(stdout);
    FileTest ft;
    const char *fileName = "test1";
    
    File *f1 = new File(fileName, "w");
    unsigned char data[] = "abcdefghijklmnopqrstuvwxyz";
    int dataLength = strlen((const char *) data)+1;
    for (int i=0; i < NUMBER_WRITES; i++) {
        length = f1->Write(data + (i % 10), 1);
    }
    if (! f1->Close()) {
        printf("ERROR: Could not close file\n");
    }
    delete f1;
    
    f1 = new File(fileName, "r");
    unsigned char buffer;
    for (int i=0; i < NUMBER_WRITES; i++) { // 38*26 bytes = 988 bytes
        length = f1->Read(&buffer, 1);
        
        if (length != 1) {
            printf("ERROR: Could not read back all bytes of file\n");
        }
        
        if (data[(i % 10)] != buffer) {
            printf("ERROR: Buffer is not equal to data written (expected= %c, actual= %c)\n",
                data[i], buffer);
        }
    }
    
    length = f1->Read(&buffer, 1);
    if (length != 0) {
        printf("ERROR: End of file not correctly reached\n");
    }
    
    if (! f1->Close()) {
        printf("ERROR: Could not close file\n");
    }
    delete f1;
}





